__author__ = 'Heiber Bustos'


import pyodbc
import sys, os.path
sys.path.append("../")

import eventsocket
from twisted.internet import defer, protocol
from twisted.application import service, internet


class protContactcenter(eventsocket.EventProtocol):


    """
        Nueva conexion desde Freeswitch. Ejecutamos la aplicacion de callcenter
    """
    @defer.inlineCallbacks
    def connectionMade(self):
        data = yield self.connect()
        yield self.myevents()

        yield self.set("contactcenter=yes")
        yield self.execute("export","contactcenter=yes")

        print data

        yield self.answer()
        yield self.hangup()

        #self.contactcenter = contactcenter()
        #camp = self.contactcenter._getCampaign(1)




class did(object):
    did_number = ""
    did_action = ""
    did_action_value = ""
    did_action_campaign_id = 0
    did_action_message_id = 0
    did_action_hangup_disconnect_cause = "NO_ROUTE_TO_DESTINATION"
    did_action_extension_number = ""
    did_action_voicemail_box = ""
    did_action_ivr_id = 0

class campaign(object):
    campaign_id = 0
    campaign_action = ""

    id = 0
    name = ""
    description = ""
    type = ""
    state = ""
    music_on_hold = ""
    call_distribution_type = ""
    recording_filename = ""
    speech_id = ""

    on_call_out_of_range_action = ""
    on_call_out_of_range_audio_id = ""
    on_call_out_of_range_campaign_id = 0
    on_call_out_of_range_answering_box = ""

    service_level = 0
    service_level_answer = 0
    on_call_action = ""
    gap_between_audios = ""
    on_call_without_agents = ""
    on_call_without_agents_audio_id = 0
    on_call_without_agents_campaign_id = 0
    on_call_without_agents_answering_box = ""

    play_welcome_audio = ""
    welcome_audio_id = 0
    max_time_on_queue = 0
    call_recording_type = ""
    cdr_id = 0
    queue_timeout = 0


class session(object):
    session_uuid = ""



class contactcenter(object):
    path_audios = ""
    continuar = True
    conn = None

    campaign = None
    did = None

    def __init__(self):
        self.path_audios = "/opt/audios"
        self.conn = pyodbc.connect('DRIVER={MySQL};Server=localhost;Port=3306;Database=ContactCenter;User=root;Password=;Option=3')


    def _getCampaign(self, id_campaign):
        sql = "SELECT * FROM Campaigns WHERE Id = " + id_campaign
        cursor = self.conn.cursor()
        cursor.execute(sql)

        if not cursor:
            return None

        row = cursor.fetchone()
        if not row:
            return None

        self.campaign = campaign()
        self.campaign.id = row.Id
        self.campaign.campaign_id = row.Id
        self.campaign.name = row.NAME
        self.campaign.description = row.Description
        self.campaign.type = row.CampaignType
        self.campaign.state = row.State
        self.campaign.music_on_hold = row.MusicOnHold
        self.campaign.call_distribution_type = row.CallDistributionType
        self.campaign.recording_filename = row.RecordingFileName
        self.campaign.speech_id = row.SpeechId

        self.campaign.on_call_out_of_range_action = row.OnCallOutOfRangeAction
        self.campaign.on_call_out_of_range_campaign_id = row.OnCallOutOfRangeCampaignId
        self.campaign.on_call_out_of_range_answering_box = row.OnCallOutOfRangeAnsweringBox
        self.campaign.on_call_out_of_range_audio_id = row.OnCallOutOfRangeAudioId

        self.campaign.service_level = row.ServiceLevel
        self.campaign.service_level_answer = row.ServiceLevelAnswer
        self.campaign.on_call_action = row.OnCallAction
        self.campaign.gap_between_audios = row.GapBetweenAudios

        self.campaign.on_call_without_agents = row.OnCallWithOutAgentsLoggedOnAction
        self.campaign.on_call_without_agents_audio_id = row.OnCallWithOutAgentsLoggedOnAudioId
        self.campaign.on_call_without_agents_answering_box = row.OnCallWithOutAgentsLoggedOnAnsweringBox
        self.campaign.on_call_without_agents_campaign_id = row.OnCallWithOutAgentsLoggedOnCampaignId

        self.campaign.play_welcome_audio = row.PlayWelcomeAudio
        self.campaign.welcome_audio_id = row.WelcomeAudioId
        self.campaign.max_time_on_queue = row.MaxTimeOnQueue
        self.campaign.call_recording_type = row.CallRecordingType
        self.campaign.cdr_id = 0
        self.campaign.queue_timeout = row.QueueTimeout

        return self.campaign


    def _validateDid(self, did):
        sql = "SELECT * FROM Did WHERE DidNumber = '" + str(did) + "'"
        cur = self.conn.cursor(sql)

        if not cur:
            return None

        row = cur.fetchone()

        if not row:
            return None

        self.did.did_number = row.DidNumber
        self.did.did_action = row.DidAction
        self.did.did_action_campaign_id = row.CampaignId
        self.did.did_action_extension_number = row.ExtensionNumber
        self.did.did_action_voicemail_box = row.VoicemailBox
        self.did.did_action_hangup_disconnect_cause = row.HangupDisconnectCause
        self.did.did_action_ivr_id = row.IvrId
        self.did.did_action_message_id = row.MessageId

        return self.did




class facContactcenter(protocol.ServerFactory):
    protocol = protContactcenter

if __name__ == '__main__':
    application = service.Application("eventsocket_server")
    internet.TCPServer(8888, facContactcenter(), interface="127.0.0.1").setServiceParent(application)

